<template>
    <div class="modal">
        <div class="mark" @click="changeIsShowLogin(false)"></div>
        <div class="loginbox">
            <div class="close" @click="changeIsShowLogin(false)"></div>
            <section class="nav">
                <a href="#" :class="{ current: isShowContent }">手机号登陆</a>
                |
                <a href="#" @click="showQrCode" :class="{ current: !isShowContent }">二维码登陆</a>
            </section>
            <div class="content">
                <div class="phonelogin" v-show="isShowContent">
                    <div class="row">
                        <input
                            type="text"
                            placeholder="请输入手机号码"
                            class="ipt"
                            v-model="phoneNum"
                        />
                    </div>
                    <div class="row">
                        <slide-verify
                            :l="42"
                            :r="20"
                            :w="362"
                            :h="140"
                            @success="onSuccess"
                            @fail="onFail"
                            @refresh="onRefresh"
                            :style="{ width: '100%' }"
                            class="slide-box"
                            ref="slideBlock"
                            :slider-text="msg"
                        ></slide-verify>
                    </div>
                    <div class="row">
                        <input type="text" placeholder="输入验证码" class="ipt" v-model="code" />
                        <!-- ***处理连续点击按钮，时间递减会变快的bug -->
                        <!-- <button class="btn btncode" @click="getCode">
                            {{ isShowCount ? `${count}s` : `获取验证码` }}
                        </button> -->
                        <button class="btn btncode" @click="getCode" v-show="!isShowCount">
                            获取验证码
                        </button>
                        <button class="btn btncode" v-show="isShowCount">
                            {{ `${count}s` }}
                        </button>
                    </div>
                    <div class="row">
                        <button class="btn btnlogin" @click="submitFn">登录</button>
                    </div>
                </div>
                <div class="erwemalogin" id="weixin" v-show="!isShowContent"></div>
            </div>
        </div>
    </div>
</template>

<script>
import { mapMutations, mapActions } from 'vuex';
import { validatePhoneNumber } from '@/utils';
import { sendSMSApi, phoneLogin, bindingPhoneAPI } from '@/request/api';
export default {
    data() {
        return {
            isShowContent: true,
            msg: '向右滑动',
            phoneNum: '',
            count: 59,
            isShowCount: false,
            //短信验证码
            code: '',
        };
    },

    methods: {
        ...mapMutations({
            changeIsShowLogin: 'showlogin/changeIsShowLogin',
            changeIsLogined: 'loginstatus/changeIsLogined',
            changeIsShowToast: 'showToast/changeIsShowToast',
        }),
        ...mapActions({
            asyncchangeIsShowToast: 'showToast/asyncchangeIsShowToast',
            asyncuodateUserInfo: 'userInfo/asyncuodateUserInfo',
        }),
        // 拼图成功
        onSuccess(times) {
            let ms = (times / 1000).toFixed(1);
            this.msg = 'login success, 耗时 ' + ms + 's';
        },
        // 拼图失败
        onFail() {
            this.onRefresh(); // 重新刷新拼图
        },
        // 拼图刷新
        onRefresh() {
            this.msg = '再试一次';
        },
        //倒计时封装
        countdown() {
            this.isShowCount = true;
            let timer = setInterval(() => {
                this.count--;
                if (this.count == 0) {
                    clearInterval(timer);
                    this.isShowCount = false;
                    this.count = 59;
                }
            }, 1000);
        },
        //提取手机号和滑块验证
        toVerity() {
            //1.正则表达式来验证手机号码
            // let reg =
            //     /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;

            //因为其他地方也会复用到这里的手机号验证，所以把这里的手机号验证抽取出来
            //所以使用工具函数（传入手机号）返回  ，成功为true，失败为false
            if (!validatePhoneNumber(this.phoneNum)) {
                // alert('请输入正确的手机号码');
                // this.changeIsShowToast({
                //     isShow:true,
                //     msg:'请输入正确的手机号码',
                //     type:'warning'
                // });
                // setTimeout(() => {
                //     this.changeIsShowToast(false);
                // }, 1500);
                this.asyncchangeIsShowToast({
                    msg: '请输入正确的手机号码',
                    type: 'warning',
                });
                return false;
            }
            //2.判断滑块验证是否通过
            if (this.msg == '向右滑动' || this.msg == '再试一次') {
                // alert('请进行滑块验证');
                this.asyncchangeIsShowToast({
                    msg: '请进行滑块验证',
                    type: 'danger',
                });
                return false;
            }
            return true;
            //内容变为倒计时 59s
            /*
            1.安装qs，
            2.api.js中编写接口方法
            3.拦截器中设置config
            4.login.vue发请求

            */
        },
        //获取验证码的点击事件
        async getCode() {
            if (!this.toVerity()) return;

            let res = await sendSMSApi({
                phone: this.phoneNum.trim(),
            });
            if (!res) return;
            if (res.code == 0) {
                // alert('短信验证码发送成功');
                this.asyncchangeIsShowToast({
                    msg: '短信验证码发送成功',
                    type: 'success',
                });
                // this.isShowCount = true;
                this.countdown();
            }
        },
        async submitFn() {
            //1.判断手机号码和滑块验证
            if (!this.toVerity()) return;

            //2.短信验证码的非空校验
            if (this.code.trim() == '') {
                // alert('请输入短信验证码');
                this.asyncchangeIsShowToast({
                    msg: '请输入短信验证码',
                    type: 'danger',
                });
                return;
            }
            let uuid = localStorage.getItem('uuid');
            let res = null;
            if (uuid) {
                res = await bindingPhoneAPI({
                    verifyCode: this.code.trim(),
                    phone: this.phoneNum.trim(),
                    uuid,
                });
            } else {
                res = await phoneLogin({
                    verifyCode: this.code.trim(),
                    phone: this.phoneNum.trim(),
                });
            }

            if (!res) return;
            // console.log('登录成功', res);

            //1.提示登录成功
            // alert('登录成功');
            this.asyncchangeIsShowToast({
                msg: '登录成功',
                type: 'success',
            });
            //2.存储token值
            localStorage.setItem('x-auth-token', res['x-auth-token']);
            //3.隐藏登录窗口
            this.changeIsShowLogin(false);
            //4.修改登录按钮变为购物车 （vuex里面的方法）
            this.changeIsLogined(true);
            //5.删除uuid
            localStorage.removeItem('uuid');
            //6.清除地址栏中的code
            this.$router.push(this.$route.path);
            //7.
            this.asyncuodateUserInfo();
        },
        showQrCode() {
            this.isShowContent = false;
            let _this = this;
            new WxLogin({
                id: 'weixin',
                appid: 'wx67cfaf9e3ad31a0d', // 这个appid要填死
                scope: 'snsapi_login',
                // 扫码成功后重定向的接口
                redirect_uri: 'https://sc.wolfcode.cn/cms/wechatUsers/shop/PC',
                // state填写编码后的url
                state: encodeURIComponent(window.btoa('http://127.0.0.1:8080' + _this.$route.path)),
                // 调用样式文件
                href: 'data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLA0KLmltcG93ZXJCb3ggLmluZm8gew0KICAgIGRpc3BsYXk6IG5vbmU7DQp9DQo=',
            });
        },
    },
};
</script>

<style lang="less" scoped>
.modal {
    width: 100%;
    height: 100%;
    position: fixed;
    left: 0;
    top: 0;
    .mark {
        width: 100%;
        height: 100%;

        background-color: rgba(0, 0, 0, 0.5);
    }
    .loginbox {
        background: url('@/assets/img/login-box-bg.png');
        position: absolute;
        top: 0;
        left: 0;
        bottom: 0;
        right: 0;
        width: 555px;
        height: 423px;
        margin: auto;
        .close {
            background: url('@/assets/img/close.png');
            width: 22px;
            height: 22px;
            position: absolute;
            right: 50px;
            top: 10px;
            cursor: pointer;
        }
        .nav {
            display: flex;
            justify-content: center;
            padding-top: 50px;
            a {
                padding: 0 10px;
                color: #9b9ab3;
                &.current {
                    color: #030303;
                }
            }
        }
        .content {
            width: 355px;
            height: 200px;
            margin: 20px auto 0;
            .phonelogin {
                .row {
                    display: flex;
                    margin-bottom: 20px;
                    .ipt {
                        outline: none;
                        flex: 1;
                        height: 48px;
                        padding-left: 10px;
                        border: 1px solid #333;
                    }
                    .btn {
                        border: none;
                        cursor: pointer;
                        line-height: 48px;
                        &.btncode {
                            margin-left: 10px;
                            width: 100px;
                            background-color: #9b9ab3;
                        }
                        &.btnlogin {
                            color: #fff;
                            width: 100%;
                            background-color: #0a328e;
                        }
                    }
                }
            }
            #weixin {
                display: flex;
                justify-content: center;
            }
        }
    }
}
/deep/.slide-box {
    width: 100%;
    position: relative;
    box-sizing: border-box;
    canvas {
        position: absolute;
        left: 0;
        top: -120px;
        display: none;
        width: 100%;
        box-sizing: border-box;
    }
    .slide-verify-block {
        width: 85px;
        height: 136px;
    }
    .slide-verify-refresh-icon {
        top: -120px;
        display: none;
    }
    &:hover {
        canvas {
            display: block;
        }
        .slide-verify-refresh-icon {
            display: block;
        }
    }
}
</style>
